import 'dart:async';

import 'package:get/get.dart';
import 'package:psi/base/base_controller.dart';
import 'package:psi/entity/common_resp.dart';
import 'package:psi/entity/request/update_password_req.dart';

import '../../../../http/api_service.dart';
import '../../../../utils/utils.dart';
import 'change_password_state.dart';

class ChangePasswordLogic extends BaseController {
  final ChangePasswordState state = ChangePasswordState();

  Timer? _timer;
  int count = 60;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    _timer?.cancel();
  }

  void sendCode() {
    state.getCode.value = true;
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      if (count == 1) {
        state.getCode.value = false;
        state.codeBtnTitle.value = "获取验证码";
        count = 60;
        _timer?.cancel();
        _timer = null;
      } else {
        count--;
        state.codeBtnTitle.value = "重新获取（$count）";
      }
    });
  }

  void goToLogin() {
    Get.back();
  }

  void changePassword() async {
    if (state.code.isEmpty) {
      showToast("请输入验证码");
      return;
    }
    if (state.password.isEmpty) {
      showToast("请输入密码");
      return;
    }
    if (state.repeatPassword.value != state.password.value) {
      showToast("两次密码输入不一致");
      return;
    }
    try {
      showLoading();
      CommonResp resp = await ApiService.request.updatePwd(UpdatePasswordReq(password: state.password.value, code: state.code.value));
      if (resp.code == 0) {
        showToast("密码修改成功");
        Get.back();
      } else {
        showToast(resp.message);
      }
      hideLoading();
    } catch(e) {
      Utils.logE(e);
      hideLoading();
    }
  }
}
